#include "Common.hpp"
#include "InetAddr.hpp"

void Usage(std::string proc){
    std::cerr << "Usage: " << proc << "server_ip server_port";
}

int main(int argc, char* argv[]){
    if(argc != 3){
        Usage(argv[0]);
        exit(USAGE_ERR);
    }

    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0){
        std::cerr << "socket error" << std::endl;
        exit(SOCKET_ERR);
    }

    InetAddr serveraddr(ip, port);
    int n = connect(sockfd, serveraddr.NetAddrPtr(), serveraddr.NetAddrLen());
    if(n < 0){
        std::cerr << "connet error" << std::endl;
        exit(CONNECT_ERR);
    }

    while(true){
        std::string input;
        std::cout << "please Enter@ " << std::endl;
        getline(std::cin, input);
        write(sockfd, input.c_str(), input.size());

        char buffer[1024];
        int m = read(sockfd, buffer, sizeof(buffer) - 1);
        if(m > 0){
            buffer[m] = 0;
            std::cout << "Server echo# " << buffer << std::endl;
        }
    }   

    close(sockfd);
    return 0;
}